package com.hllxd.hism.star.basic.service.collect;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

/**
 * @author lixiyong01
 * @date 20210817
 */
public class HttpUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    public static String get(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.info("Get Exception: {}.", e.toString());
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                logger.error("Exception: {}", e2.toString());
            }
        }
        return result;
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @throws IOException
     */
    public static String getSynchronized(URL url) throws IOException {
        BufferedReader in = null;
        try {
            logger.debug("==>(GET)  Request: " + url.toString());
            // 打开和URL之间的连接
            URLConnection connection = url.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }

    public static String get(String url, Map<String, String> requestParams) throws IOException {
        if (requestParams != null && requestParams.size() != 0) {
            url = url + "?" + buildParamStr(requestParams);
        }
        logger.info("request: {}.", url);
        long start = System.currentTimeMillis();
        String res = getSynchronized(new URL(url));
        logger.info("respond: {},costTime:{}ms", res.length(), (System.currentTimeMillis() - start));
        return res;
    }

    public static String buildParamStr(Map<String, String> requestParams) {
        String retStr = "";
        if (requestParams == null || requestParams.size() == 0) {
            return retStr;
        }
        for (String key : requestParams.keySet()) {
            String value = requestParams.get(key);
            if (retStr.length() != 0) {
                retStr += '&';
            }
            retStr += key + '=' + value;

        }
        return retStr;
    }


}
